﻿using System.Net.Http;
using AutoMapper;
using Common.Commands.MemberCommands;
using Dto.ApiRequests.MemberForms;
using Sanelib.Dto;
using WebApp.Services;

namespace WebApp.ControllerApis
{
    public class AuthController : SmartApiController
    {
        private readonly IAuthenticationService _authenticationService;

        public AuthController(IUserSession userSession, IMappingEngine mappingEngine, IAuthenticationService authenticationService)
            : base(userSession, mappingEngine)
        {
            _authenticationService = authenticationService;
        }

        public HttpResponseMessage Post(LoginForm form)
        {
            var errors = new ErrorResult();
            var message = string.Empty;

            if (UserSession.Login(form, ref message))
            {
                return Content(WebApiResonseBase.Create("/Home", true));
            }

            errors.AddError("Username or Password", message);
            return Content(errors);
        }

        public HttpResponseMessage Put(ChangePasswordForm form)
        {
            var validator = new ErrorResult();

            var user = GetCurrentUser();
            var success = user != null && _authenticationService.PasswordMatches(user, form.OldPassword);

            if (!success)
            {
                validator.AddError("OldPassword or NewPassword or ConfirmPassword", "is Invalid");
                return Content(validator);
            }

            var command = new ChangePassword
            {
                Id = user.Id,
                OldPassword = form.OldPassword,
                NewPassword = form.NewPassword,
                ConfirmPassword = form.ConfirmPassword,
            };

            return ExecuteCommand(command);
        }

        //TODO: Implement for revoking member access. Must be admin user can call this. (Block Member)
        //public HttpResponseMessage Delete(string userName)
        //{

        //}
    }
}